package com.cherish.meeting.api.controller;


import com.cherish.meeting.api.service.IUserInfoService;
import com.cherish.meeting.api.service.WxService;
import com.cherish.meeting.common.api.HttpResult;
import com.cherish.meeting.common.exception.BussException;
import com.cherish.meeting.common.util.StringUtil;
import com.cherish.meeting.db.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-03-02
 */
@Slf4j
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private WxService wxService;

    @GetMapping("/getUser")
    public HttpResult getUser(HttpServletRequest request) {
        String openid = request.getParameter("openid");
        String code = request.getParameter("code");
        try {
            log.info("获取用户信息openid=[{}],code=[{}]", openid, code);
            if (StringUtil.isEmpty(openid)) {
                openid = wxService.getOpenId(code);
            }
            if (StringUtil.isEmpty(openid)) {
                log.info("openid获取失败");
                throw new BussException("openid获取失败");
            }
            UserInfo userInfo = userInfoService.selectByOpenid(openid);
            return HttpResult.success("用户查询成功").setData(userInfo);
        } catch (BussException e) {
            return HttpResult.failed(e.getMessage());
        } catch (Exception e) {
            log.error("用户查询失败：系统异常,{}", e.getMessage());
            return HttpResult.failed("用户查询失败：系统异常");
        }
    }

    @GetMapping("/bindUser")
    public HttpResult bindUser(HttpServletRequest request) {
        UserInfo userInfo = new UserInfo();
        String openid = request.getParameter("openid");
        String name = request.getParameter("name");
        String mobile = request.getParameter("mobile");
        String code = request.getParameter("code");

        if (StringUtil.isEmpty(openid)) {
            openid = wxService.getOpenId(code);
        }
        if (StringUtil.isEmpty(openid)) {
            log.info("openid获取失败");
            throw new BussException("openid获取失败");
        }
        userInfo.setOpenid(openid).setName(name).setMobile(mobile);
        try {
            userInfo = userInfoService.saveOrUpdate(userInfo);
            return HttpResult.success("用户绑定成功").setData(userInfo);
        } catch (BussException e) {
            return HttpResult.failed(e.getMessage());
        } catch (Exception e) {
            log.error("用户绑定失败：系统异常,{}", e.getMessage());
            return HttpResult.failed("用户绑定失败：系统异常");
        }
    }

}
